import BatchOperation from "@/components/BatchOperation";
import PermissionControl from "@/components/PermissionControl/index";
import { batchIntegralChangeRequest, integralChangeRequest } from "@/services/patient/integralApi";
import { getPatientList } from "@/services/patient/patientApi";
import { showMsg } from "@/utils/utils";
import { ModalForm, ProFormDigit } from "@ant-design/pro-form";
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table";
import { Button, Upload } from "antd";
import { useRef, useState } from "react";
import styles from './style.less';

const ManageTab = () => {

  const actionRef = useRef<ActionType>();
  const [open, setOpen] = useState<boolean>(false);
  const [type, setType] = useState<number>(1);
  const [batch, setBatch] = useState<boolean>(false);
  const [selectedRows, setSelectedRows] = useState<React.Key[]>([]);
  const [editRowData, setEditRowData] = useState<PATIENT.PatientInfo>();

  const columns: ProColumns<PATIENT.PatientInfo>[] = [
    {
      title: '患者编号',
      dataIndex: 'patient_id',
      colSize: 2.5
    },
    {
      title: '姓名',
      dataIndex: 'patient_name',
      colSize: 2.5
    },
    {
      title: '身份证/住院号',
      dataIndex: 'identity_no',
      colSize: 3
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      colSize: 2.5
    },
    {
      title: '积分',
      dataIndex: 'total_integral',
      search: false
    },
    {
      title: '可用积分',
      dataIndex: 'available_integral',
      search: false
    },
    {
      title: '等级',
      dataIndex: 'rank',
      search: false
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: '15%',
      render: (_, record) => [
        <div key="batch" style={{ display: 'inline-flex', gap: 24 }}>
          <PermissionControl key="add" action_id="900901008">
            <a onClick={() => { setEditRowData(record); setType(1); setOpen(true); }}>添加积分</a>
          </PermissionControl>
          <PermissionControl key="sub" action_id="900901009">
            <a onClick={() => { setEditRowData(record); setType(0); setOpen(true); }}>扣减积分</a>
          </PermissionControl>
        </div >
      ]
    }
  ];

  const cleanModalState = () => {
    setEditRowData(undefined);
    setBatch(false);
    setOpen(false);
  };

  const onFinish = async ({ integral, submit_explain }: FormDataType) => {
    integral = type === 1 ? integral : -integral;
    try {
      if (batch) {
        await batchIntegralChangeRequest({ patient_id_list: selectedRows as string[], integral, submit_explain });
      } else {
        const { identity_no = '', mobile, patient_id, patient_name = '', address } = editRowData || {};
        const actionId = type === 1 ? '900901008' : '900901009';
        await integralChangeRequest({ identity_no, mobile, patient_id, patient_name, address, integral, submit_explain }, actionId);
      }
      showMsg('提交成功', 'success');
      cleanModalState();
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
    }
  };

  return <>
    <ProTable<PATIENT.PatientInfo>
      actionRef={actionRef}
      rowKey="patient_id"
      className='mytable'
      cardProps={{ style: { paddingTop: 0 } }}
      options={false}
      bordered
      columns={columns}
      search={{
        span: 2,
        labelWidth: 'auto',
        collapsed: false,
        collapseRender: false,
        style: { padding: '0 6px 0 20px' },
        optionRender: (_, __, [, queryBtn]) => [queryBtn]
      }}
      request={async (params) => {
        try {
          const res = await getPatientList({ ...params });
          return { success: true, data: res.record_list, total: res.sum_record_num };
        } catch (reason) {
          return { success: false, data: [] };
        }
      }}
      toolbar={{ style: { borderTop: '4px solid #f0f2f5', paddingTop: 8 } }}
      toolBarRender={() => [
        <div key="batch" style={{ display: "inline-flex", gap: 12, alignItems: "center" }}>
          <PermissionControl action_id="900901007">
            <BatchOperation
              onChange={() => actionRef.current?.clearSelected?.()}
              onOk={async option => {
                if (selectedRows?.length === 0) {
                  showMsg('请选择数据');
                  return;
                }
                setType(option.value); setBatch(true); setOpen(true);
              }}
              options={[
                { value: 1, label: '添加', confirm: false },
                { value: 0, label: '扣减', confirm: false }
              ]}
            />
          </PermissionControl>
          <PermissionControl action_id="900901012">
            <Upload
              action="/api/patient/integral/approval/file"
              accept=".xls,.xlsx"
              maxCount={1}
              className={styles.uploadFile}
              onChange={({ file: { status, response } }) => {
                if (status === 'error') {
                  showMsg(response?.errmsg);
                  return;
                }
                if (status === 'done') {
                  showMsg('导入成功', 'success');
                  actionRef.current?.reload();
                }
              }}
              headers={{
                'Action_Id': '900901012',
                'Oper-Token': localStorage.getItem('Oper-Token') ?? ''
              }}>
              <Button type="primary">导入修改</Button>
            </Upload>
          </PermissionControl>
        </div>
      ]}
      rowSelection={{ onChange: setSelectedRows }}
      pagination={{ showQuickJumper: true }}
    />
    <ModalForm<FormDataType>
      width={400}
      layout="horizontal"
      visible={open}
      title={`${batch ? '批量' : ''}${operationType[type]}积分`}
      modalProps={{ maskClosable: false, destroyOnClose: true, onCancel: cleanModalState }}
      onFinish={onFinish}
    >
      <ProFormDigit
        name="integral" label={operationType[type]} wrapperCol={{ span: 21 }} addonAfter={<>积分</>} placeholder="请输入数值"
        required={false} min={1} rules={[{ required: true, message: '请输入积分数值' }]}
      />
      {/* <ProFormTextArea name="submit_explain" label="说明" wrapperCol={{ span: 21 }} /> */}
    </ModalForm>
  </>;
};

export default ManageTab;

const operationType = ['扣减', '添加'];

type FormDataType = { integral: number, submit_explain: string };
